package com.koushikdutta.ion.loader;

import android.text.TextUtils;
import com.koushikdutta.async.DataEmitter;
import com.koushikdutta.async.future.Future;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.async.http.AsyncHttpRequest;
import com.koushikdutta.async.http.AsyncHttpResponse;
import com.koushikdutta.async.http.callback.HttpConnectCallback;
import com.koushikdutta.async.http.libcore.RawHeaders;
import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.Loader.LoaderEmitter;

public class HttpLoader extends SimpleLoader {
    public Future<DataEmitter> load(Ion ion, AsyncHttpRequest request, final FutureCallback<LoaderEmitter> callback) {
        if (request.getUri().getScheme().startsWith("http")) {
            return ion.getHttpClient().execute(request, new HttpConnectCallback() {
                public void onConnectCompleted(Exception ex, AsyncHttpResponse response) {
                    long length = -1;
                    int loadedFrom = 3;
                    RawHeaders headers = null;
                    AsyncHttpRequest request = null;
                    if (response != null) {
                        request = response.getRequest();
                        headers = response.getHeaders().getHeaders();
                        length = response.getHeaders().getContentLength();
                        String servedFrom = response.getHeaders().getHeaders().get("X-Served-From");
                        if (TextUtils.equals(servedFrom, "cache")) {
                            loadedFrom = 1;
                        } else if (TextUtils.equals(servedFrom, "conditional-cache")) {
                            loadedFrom = 2;
                        }
                    }
                    callback.onCompleted(ex, new LoaderEmitter(response, length, loadedFrom, headers, request));
                }
            });
        }
        return null;
    }
}
